package system

import (
	"encoding/json"
	"fmt"
	"ltbz/cultural_tourism_api/controllers"
	"ltbz/cultural_tourism_api/models"
	"ltbz/cultural_tourism_api/models/system"
	systemServices "ltbz/cultural_tourism_api/services/system"
	"ltbz/cultural_tourism_api/utils"
	"strconv"
	"strings"
	"time"
)

// 系统用户管理
type SysUserController struct {
	controllers.BaseAuthController
}

// @Tags 系统模块
// @Title 新增用户
// @Description 新增用户
// @Param	request	body system.SysUserAddReq true "type json string"
// @Success 200
// @router /user/add [post]
func (this *SysUserController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysUserAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.SysUserName == "" {
		br.Msg = "请输入账号！"
		return
	}

	if req.Password == "" {
		br.Msg = "请输入密码！"
		return
	}

	// 判断账号名是否已存在
	item := new(system.SysUser)
	existSysUser, err := item.GetSysUserBySysUserName(req.SysUserName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查询管理员信息失败！"
		br.ErrMsg = "查询管理员信息失败，Err:" + err.Error()
		return
	}
	if existSysUser != nil && existSysUser.SysUserId > 0 {
		br.Msg = "用户名重复,请重新设置！"
		br.ErrMsg = "用户名重复,请重新设置！"
		return
	}
	// 判断手机号是否已存在
	existSysUserFromMobile, err := item.GetSysUserByMobile(req.Mobile)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查询管理员信息失败！"
		br.ErrMsg = "查询管理员信息失败，Err:" + err.Error()
		return
	}
	if existSysUserFromMobile != nil && existSysUserFromMobile.SysUserId > 0 {
		br.Msg = "手机号已被其他账号绑定，请重新设置"
		br.ErrMsg = "手机号已被其他账号绑定，请重新设置"
		return
	}

	req.Password = utils.MD5(req.Password + utils.PwdPrefix)

	//todo 验证部门信息
	//todo 验证角色信息
	// 新增账号
	item = &system.SysUser{
		SysUserName:   req.SysUserName,
		RealName:      req.RealName,
		Password:      req.Password,
		Enabled:       req.Enabled,
		Email:         req.Email,
		Mobile:        req.Mobile,
		DeptId:        req.DeptId,
		RoleId:        req.RoleId,
		Position:      req.Position,
		Remark:        req.Remark,
		LastLoginTime: time.Now(),
		DisableTime:   time.Now(),
		CreateTime:    time.Now(),
		ModifyTime:    time.Now(),
		CampusId:      req.CampusId,
		CampusName:    req.CampusName,
		ClassId:       req.ClassId,
		ClassName:     req.ClassName,
		ScenicSpotId:  req.ScenicSpotId,
	}
	_, err = item.Add()
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Msg = "保存成功"
	br.Ret = 200
	return
}

// @Tags 系统模块
// @Title 获取用户列表
// @Description 获取用户列表
// @Param	request	body system.SysAdminListReq true "type json string"
// @Success 200
// @router /user/list [post]
func (this *SysUserController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysUserListReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.PageSize <= 0 {
		req.PageSize = utils.PageSize20
	}
	if req.CurrentIndex <= 0 {
		req.CurrentIndex = 1
	}

	startSize := utils.StartIndex(req.CurrentIndex, req.PageSize)

	var total int
	resp := new(system.SysUserPageResp)
	page := utils.GetPaging(req.CurrentIndex, req.PageSize, total)

	item := new(system.SysUser)

	condition := ""
	var pars []interface{}
	var tmpList []*system.SysUserListTmpItem
	var list []*system.SysUserListItem

	if req.DeptId > 0 {
		deptIds, err := systemServices.GetDeptAllIds(req.DeptId)
		if err != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		if len(deptIds) > 0 {

			condition += " AND a.dept_id IN ("
			for i := 0; i < len(deptIds); i++ {
				condition += "?,"
			}
			condition = strings.Trim(condition, ",")
			condition += ")"
			pars = append(pars, deptIds)
		} else {
			resp.Paging = page
			br.Msg = "获取成功"
			br.Ret = 200
			return
		}
	}
	if req.KeyWord != "" {
		keyLike := `%` + req.KeyWord + `%`
		condition += " AND (a.real_name LIKE ? OR a.mobile LIKE ? OR a.sys_user_name LIKE ?) "
		pars = append(pars, keyLike, keyLike, keyLike)
	}

	if req.Enabled > -1 {
		condition += " AND a.enabled = ? "
		pars = append(pars, req.Enabled)
	}

	total, err = item.GetSysUserPageCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	tmpList, err = item.GetSysUserPage(condition, pars, startSize, req.PageSize)
	if err != nil {
		br.Msg = "获取失败！"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	fmt.Println(len(tmpList))
	if len(tmpList) > 0 {
		deptNameMap, err, errMsg := systemServices.GetChildDeptNames()
		if err != nil {
			br.Msg = "获取失败！"
			br.ErrMsg = "获取失败，Err:" + err.Error() + ";errMsg:" + errMsg
			return
		}
		for _, v := range tmpList {
			tmp := &system.SysUserListItem{
				SysUserId:    v.SysUserId,
				SysUserName:  v.SysUserName,
				RealName:     v.RealName,
				Enabled:      v.Enabled,
				Email:        v.Email,
				Mobile:       v.Mobile,
				DeptId:       v.DeptId,
				RoleId:       v.RoleId,
				RoleName:     v.RoleName,
				Position:     v.Position,
				Remark:       v.Remark,
				CreateTime:   v.CreateTime.Format(utils.FormatDateTime),
				ModifyTime:   v.ModifyTime.Format(utils.FormatDateTime),
				ScenicSpotId: v.ScenicSpotId,
			}

			if name, ok := deptNameMap[v.DeptId]; ok {
				tmp.DeptFullName = name
			}
			list = append(list, tmp)
		}
	} else {
		fmt.Println("len(tmpList)", len(tmpList))
	}
	page = utils.GetPaging(req.CurrentIndex, req.PageSize, total)
	resp.Paging = page
	resp.List = list
	br.Msg = "获取成功"
	br.Ret = 200
	br.Data = resp
	return
}

// @Tags 系统模块
// @Title 修改密码
// @Description 修改密码
// @Param	request	body system.ModifyPwdReq true "type json string"
// @Success 200
// @router /user/modify/pwd [post]
func (this *SysUserController) ModifyPwd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.ModifyPwdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	//获取jwt数据失败
	var sysUserInfo *system.SysUser
	// 判断账号名是否已存在
	sysUser := new(system.SysUser)
	//查询账号是否存在
	sysUserInfo, err = sysUser.GetSysUserBySysUserId(req.SysUserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "账号不存在！"
			br.ErrMsg = "账号不存在"
			return
		}
		br.Msg = "查询管理员信息失败！"
		br.ErrMsg = "查询管理员信息失败,Err:" + err.Error()
		return
	}

	if req.Pwd != req.ConfirmPwd {
		br.Msg = "新密码两次输入不一致，请核对！"
		br.ErrMsg = "新密码两次输入不一致，请核对"
		return
	}

	req.Pwd = utils.MD5(req.Pwd + utils.PwdPrefix)

	if sysUserInfo.Password == req.Pwd {
		br.Msg = "新密码不能与旧密码一致，请重试"
		br.ErrMsg = "新密码不能与旧密码一致，请重试"
		return
	}
	sysUserInfo.Password = req.Pwd

	updateParams := make(map[string]interface{})
	whereParam := make(map[string]interface{})

	updateParams["password"] = req.Pwd
	//生成token
	token := utils.GenToken(strconv.Itoa(int(req.SysUserId)) + sysUserInfo.SysUserName)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败，生成token出错"
		return
	}

	updateParams["token"] = token

	whereParam["sys_user_id"] = sysUserInfo.SysUserId

	err = sysUserInfo.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "密码更新失败"
		br.ErrMsg = "密码更新失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "修改成功"
	return
}

// @Tags 系统模块
// @Title 修改我的密码
// @Description 修改我的密码
// @Param	request	body system.ModifyMyPwdReq true "type json string"
// @Success 200
// @router /user/modify/my/pwd [post]
func (this *SysUserController) ModifyMyPwd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.ModifyMyPwdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	req.NewPwd = utils.MD5(req.NewPwd + utils.PwdPrefix)
	req.ConfirmPwd = utils.MD5(req.ConfirmPwd + utils.PwdPrefix)

	sysUserInfo := this.SysUser

	if req.NewPwd != req.ConfirmPwd {
		br.Msg = "新密码两次输入不一致，请核对！"
		return
	}

	if sysUserInfo.Password != req.OldPwd {
		br.Msg = "旧密码错误，请重新输入"
		return
	}
	if sysUserInfo.Password == req.NewPwd {
		br.Msg = "新密码不能与旧密码一致，请重试"
		return
	}
	sysUserInfo.Password = req.NewPwd

	updateParams := make(map[string]interface{})
	updateParams["password"] = req.NewPwd
	//生成token
	token := utils.GenToken(strconv.Itoa(int(sysUserInfo.SysUserId)) + sysUserInfo.SysUserName)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败，生成token出错"
		return
	}

	updateParams["token"] = token

	whereParam := make(map[string]interface{})
	whereParam["sys_user_id"] = sysUserInfo.SysUserId

	err = sysUserInfo.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "密码更新失败"
		br.ErrMsg = "密码更新失败,Err:" + err.Error()
		return
	}
	br.Msg = "修改成功"
	br.Ret = 200
	return
}

// @Tags 系统模块
// @Title 修改我的初始密码
// @Description 修改我的初始密码
// @Param	request	body system.ModifyMyInitPwdReq true "type json string"
// @Success 200
// @router /user/modify/my/init_pwd [post]
func (this *SysUserController) ModifyMyInitPwd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.ModifyMyPwdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	sysUserInfo := this.SysUser
	req.NewPwd = utils.MD5(req.NewPwd + utils.PwdPrefix)
	req.ConfirmPwd = utils.MD5(req.ConfirmPwd + utils.PwdPrefix)

	if req.NewPwd != req.ConfirmPwd {
		br.Msg = "新密码两次输入不一致，请核对"
		br.ErrMsg = "新密码两次输入不一致，请核对,Err:" + err.Error()
		return
	}
	if sysUserInfo.Password == req.NewPwd {
		br.Msg = "新密码不能与旧密码一致，请重试"
		br.ErrMsg = "新密码不能与旧密码一致，请重试,Err:" + err.Error()
		return
	}
	sysUserInfo.Password = req.NewPwd

	updateParams := make(map[string]interface{})
	updateParams["password"] = req.NewPwd

	whereParam := make(map[string]interface{})
	whereParam["sys_user_id"] = sysUserInfo.SysUserId

	err = sysUserInfo.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "密码更新失败"
		br.ErrMsg = "密码更新失败,Err:" + err.Error()
		return
	}

	br.Msg = "修改成功"
	br.Ret = 200
	return
}

// @Tags 系统模块
// @Title 删除用户
// @Description 删除用户
// @Param	request	body system.SysAdminReq true "type json string"
// @Success 200
// @router /user/del [post]
func (this *SysUserController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysAdminReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	item := new(system.SysUser)
	item.SysUserId = req.SysUserId
	err = item.Delete()
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Msg = "删除成功"
	br.Ret = 200
}

// @Tags 系统模块
// @Title 编辑用户
// @Description 编辑用户
// @Param	request	body system.SysUserEditReq true "type json string"
// @Success 200
// @router /user/edit [post]
func (this *SysUserController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysUserEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	// 判断账号名是否已存在
	admin := new(system.SysUser)
	//查询账号是否存在
	item, err := admin.GetSysUserBySysUserId(req.SysUserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "账号不存在！"
			return
		}
		br.Msg = "查询管理员信息失败！"
		br.ErrMsg = "查询管理员信息失败,Err:" + err.Error()
		return
	}
	var resetToken bool
	if item.SysUserName != req.SysUserName {
		_, err = item.GetSysUserBySysUserName(req.SysUserName)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "查询管理员信息失败！"
			br.ErrMsg = "查询管理员信息失败,Err:" + err.Error()
			return
		}
		if err == nil {
			br.Msg = "用户名重复，请重新设置！"
			br.ErrMsg = "用户名重复，请重新设置,Err:" + err.Error()
			return
		}
		resetToken = true
	}
	if item.Mobile != req.Mobile {
		// 判断手机号是否已存在
		_, err = item.GetSysUserByMobile(req.Mobile)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "查询管理员信息失败！"
			br.ErrMsg = "查询管理员信息失败,Err:" + err.Error()
			return
		}
		if err == nil {
			br.Msg = "手机号已被其他账号绑定，请重新设置！"
			br.ErrMsg = "手机号已被其他账号绑定，请重新设置,Err:" + err.Error()
			return
		}
		resetToken = true
	}

	//todo 验证部门信息
	//todo 验证角色信息
	// 更新账号
	item.SysUserName = req.SysUserName
	item.RealName = req.RealName
	item.Enabled = req.Enabled
	item.Email = req.Email
	item.Mobile = req.Mobile
	item.DeptId = req.DeptId
	item.RoleId = req.RoleId
	item.Position = req.Position
	item.Remark = req.Remark
	if req.Enabled == 0 {
		item.DisableTime = time.Now()
	}

	updateParams := make(map[string]interface{})
	updateParams["sys_user_name"] = req.SysUserName
	updateParams["real_name"] = req.RealName
	updateParams["enabled"] = req.Enabled
	updateParams["email"] = req.Email
	updateParams["mobile"] = req.Mobile
	updateParams["dept_id"] = req.DeptId
	updateParams["role_id"] = req.RoleId
	updateParams["position"] = req.Position
	updateParams["remark"] = req.Remark
	updateParams["campus_id"] = req.CampusId
	updateParams["campus_name"] = req.CampusName
	updateParams["class_id"] = req.ClassId
	updateParams["class_name"] = req.ClassName
	updateParams["scenic_spot_id"] = req.ScenicSpotId

	if resetToken {
		//生成token
		token := utils.GenToken(strconv.Itoa(int(req.SysUserId)) + item.SysUserName)
		if err != nil {
			br.Msg = "编辑失败"
			br.ErrMsg = "编辑失败，生成token出错"
			return
		}

		updateParams["token"] = token
	}

	whereParam := make(map[string]interface{})
	whereParam["sys_user_id"] = req.SysUserId

	err = item.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "修改成功"
	return
}

// @Tags 系统模块
// @Title 修改管理员状态
// @Description 修改管理员状态
// @Param	request	body system.SysAdminModifyEnabledReq true "type json string"
// @Success 200
// @router /user/modify/enabled [post]
func (this *SysUserController) ModifyEnabled() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req system.SysAdminModifyEnabledReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	admin := new(system.SysUser)
	admin.SysUserId = req.SysUserId
	admin.Enabled = req.Enabled

	updateParams := make(map[string]interface{})
	updateParams["enabled"] = req.Enabled
	updateParams["disable_time"] = time.Now()

	whereParam := make(map[string]interface{})
	whereParam["sys_user_id"] = req.SysUserId

	err = admin.Update(updateParams, whereParam)
	if err != nil {
		br.Msg = "更新失败！"
		br.ErrMsg = "更新失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "修改成功！"
	return
}
